package com.raising.modules.sys.controller;

import com.google.common.collect.Lists;
import com.raising.StaticParam;
import com.raising.framework.controller.BaseController;
import com.raising.framework.entity.ResultCode;
import com.raising.framework.entity.ResultVo;
import com.raising.framework.interceptor.Page;
import com.raising.modules.sys.entity.Organization;
import com.raising.modules.sys.entity.Role;
import com.raising.modules.sys.entity.User;
import com.raising.modules.sys.service.OrganizationService;
import com.raising.modules.sys.service.RoleService;
import com.raising.modules.sys.service.UserService;
import com.raising.modules.sys.utils.OrgUtils;
import com.raising.modules.sys.utils.SysConfigUtil;
import com.raising.utils.JCacheUtils;
import com.raising.utils.JStringUtils;
import com.raising.utils.UserUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.List;

/**
 * 用户管理
 * @author GaoYuan
 * @datetime 2018/2/23 上午11:23
 */
@Controller
@RequestMapping("${adminPath}/sys/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationService organizationService;
	@Autowired
	private RoleService roleService;

	/**
	 * 跳转用户列表
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "/list")
	public String list(Model model) {
		List<Organization> organizationList = OrgUtils.getMyOrgList();
		model.addAttribute("organizationList", organizationList);
		olog("进入用户管理页面");
		return "sys/user/list";
	}


	/**
	 * 加载用户列表
	 * @author GaoYuan
	 * @datetime 2018/1/16 下午8:44
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "/getPage.json",method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public ResultVo getPage(User user, Model model, Page<User> page) throws Exception {
		if(!OrgUtils.isMyOrg(user.getOrgId()) || JStringUtils.isBlank(user.getOrgId())){
			user.setOrgId(OrgUtils.getMyOrgId());
		}
		//查询选择的机构以及所属机构
		user.setOrgId(user.getOrgId());
		user.setOrgNoQuery(OrgUtils.getNoById(user.getOrgId()));
		page.setEntity(user);
		return ResultVo.success().data(userService.getPage(page));
	}

	/**
	 * 跳转用户详情页面
	 * @author lirg
	 * @datetime 2018/1/14 17:47
	 * @param
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "/view", method = RequestMethod.GET)
	public String view(String id, Model model) throws Exception{
		User user = userService.get(id);
		model.addAttribute("user", user);
		olog("查看用户["+user.getName()+"]详情","{id:"+user.getId()+"}");
		return "sys/user/view";
	}

	/**
	 * 跳转到新增页面
	 * @author gaoyuan
	 * @param
	 * @param model
	 * @return
	 */
	@RequiresPermissions("sys:user:create")
	@RequestMapping(value = "/create", method = RequestMethod.GET)
	public String create(Model model) throws Exception{
		model.addAttribute("user",new User());
		model.addAttribute("organizationList", OrgUtils.getMyOrgList());
		model.addAttribute("roleList", roleService.getList(new Role()));
		return "sys/user/add";
	}

	/**
	 * 提交新增账户信息
	 * @author GaoYuan
	 * @datetime 2018/1/16 下午2:20
	 */
	@RequiresPermissions("sys:user:create")
	@RequestMapping(value = "/insert.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo insert(User user) {
		if(!OrgUtils.isMyOrg(user.getOrgId()) ){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限设置").data(user.getOrgId());
		}
		//不是部门经理，不能修改，超级管理员可以修改，自己的信息可以修改
		User loginUser = UserUtils.getLoginUser();
		if(loginUser.isAdmin() || loginUser.getIsDept()){
			user.setLocked(false);
			user.setIsDept(false);
			user.setStatus(StaticParam.VALID_STRING);
			userService.insert(user);
			olog("新增用户["+user.getUsername()+"]",user.toString());
			return ResultVo.success().desc("添加成功").data(user.getId());
		}else{
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限修改");
		}
	}

	/**
	 * 跳转到人员信息编辑页面
	 * @param id
	 * @param model
	 * @author GaoYuan
	 * @datetime 2018/1/16 上午8:43
	 */
	@RequiresPermissions("sys:user:update")
	@RequestMapping(value = "/update", method = RequestMethod.GET)
	public String update(String id,Model model) throws Exception{
		//判断是否有人员表信息，如果没有，则新建，有则直接查出
		User user = userService.get(id);
		model.addAttribute("user",user);
		model.addAttribute("organizationList", OrgUtils.getMyOrgList());
		model.addAttribute("roleList", roleService.getList(new Role()));
		model.addAttribute("currentTime", System.currentTimeMillis());
		return "sys/user/edit";
	}

	/**
	 * 提交编辑账户信息
	 * @author GaoYuan
	 * @datetime 2018/1/16 下午2:20
	 */
	@RequiresPermissions("sys:user:update")
	@RequestMapping(value = "/update.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo update(String id,String username,String name,String password,String orgId,
						   String roleIdsStr,String locked,String is_dept,String sexCd) throws Exception{
		User old = userService.get(id);
		if(old == null){
			return ResultVo.failure(ResultCode.RECORD_EMPTY).desc("数据不存在");
		}
		if(!OrgUtils.isMyOrg(old.getOrgId())){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限操作此数据").data(id);
		}
		if(!OrgUtils.isMyOrg(orgId)){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限绑定该单位").data(id);
		}

		JCacheUtils.remove(username);
		User user = new User();
		user.setId(id);
		user.setUsername(username);
		user.setPassword(password);
		user.setName(name);
		user.setSexCd(sexCd);
		user.setRoleIdsStr(roleIdsStr);
		if(StaticParam.YES_STRING.equals(locked)){
			user.setLocked(true);
		}else{
			user.setLocked(false);
		}
		user.setOrgId(orgId);
		userService.updateMain(user);
		olog("修改用户["+old.getUsername()+"]信息",user.toString());
		return ResultVo.success().desc("修改成功");
	}

	/**
	 * 用户删除
	 * @author gaoyuan
	 * @param id 用户标识
	 * @return
	 */
	@RequiresPermissions("sys:user:delete")
	@RequestMapping(value = "/delete.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo delete(String id) throws Exception{
		User old = userService.get(id);
		if(old == null){
			return ResultVo.success().desc("数据已删除").data(id);
		}
		if(!OrgUtils.isMyOrg(old.getOrgId())){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限删除该数据").data(id);
		}
		if("1".equals(id)){
			return ResultVo.failure(ResultCode.NO_PERMISSIONS).desc("没有权限修改").data("failure");
		}
		userService.delete(id);
		olog("删除用户["+old.getUsername()+"]",old.toString());
		return ResultVo.success().desc("删除成功").data(id);
	}

	/**
	 * ajax通过条件如单位加载用户list
	 * @author lirg
	 * @TrainAssess 2018/1/17 16:32
	 * @param
	 */
	@RequiresPermissions("sys:user:view")
	@RequestMapping(value = "/getList.json",method = {RequestMethod.POST,RequestMethod.GET})
	@ResponseBody
	public ResultVo getList(User user) {
		user.setOrderBy(" a.name ");
		List<User> userList = userService.selectUserInfoToList(user);
		return ResultVo.success().desc("成功").data(userList);
	}


	/**
	 * 跳转到个人资料页面【self】
	 * @author GaoYuan
	 * @datetime 2018/1/20 上午9:10
	 * 并不需要权限，因为所有人都有
	 */
	@RequestMapping(value = "/self", method = RequestMethod.GET)
	public String self(Model model) throws Exception {
		olog("查看个人资料");
		String userId = UserUtils.getUserId();
		//判断是否有人员表信息，如果没有，则新建，有则直接查出
		User user = userService.get(userId);

		model.addAttribute("user",user);

		model.addAttribute("organizationList", organizationService.getList(new Organization()));

		model.addAttribute("currentTime", System.currentTimeMillis());
		return "sys/user/self";
	}

	/**
	 * 更新个人信息【self】
	 * @author GaoYuan
	 * @datetime 2018/1/20 上午9:10
	 * 并不需要权限，因为所有人都有
	 */
	@RequestMapping(value = "/updateSelf.json", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo updateSelf(User user) {
		if(JStringUtils.isBlank(user.getOrgId())){
			return ResultVo.failure(ResultCode.PARAM_EMPTY).desc("单位不能为空");
		}
		if(JStringUtils.isBlank(user.getName())){
			return ResultVo.failure(ResultCode.PARAM_EMPTY).desc("姓名不能为空");
		}
		//为了安全，把敏感字段处理掉
		user.setUsername(null);
		user.setRoleIdsStr(null);
		user.setRoleIds(null);
		user.setLocked(null);
		user.setIsDept(null);

		userService.updateSelf(user);
		olog("更新个人资料信息",user.toString());
		return ResultVo.success().desc("修改成功");
	}


	/**
	 * 管理员 更新指定用户头像 user/id.png
	 * @author GaoYuan
	 * @datetime 2018/1/27 下午5:04
	 */
	@RequestMapping(value = "/uploadHeadImg", method = RequestMethod.POST)
	public @ResponseBody String uploadHeadImg(@RequestParam("file") MultipartFile[] files,
							  HttpServletRequest request,String userId) {
		List<String> list = Lists.newArrayList();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
//				list = saveFile(request, file, list);
				// 判断文件是否为空
				if (!file.isEmpty()) {
					try {
						// 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
						// )
						String savePathPre = SysConfigUtil.getConfigValueByKey("UPLOAD_SAVE_PATH_IMG","");
						String readPath = "/user/"+userId+".png";
						String filePath = savePathPre + readPath;

						File saveDir = new File(filePath);
						File oldFile = new File(filePath);
						if (!saveDir.getParentFile().exists()){
							saveDir.getParentFile().mkdirs();
						}
						if(oldFile.exists()){
							oldFile.delete();
						}
						// 转存文件
						file.transferTo(saveDir);
						list.add(readPath);

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			if(list.size()>0){
				User user = new User();
				user.setId(userId);
				user.setPhoto(list.get(0));
				userService.updateHeadImg(user);
				olog("更新用户[iD="+userId+"]头像","{id:"+userId+"}");
			}
		}
		//跳转的页面
		return "<script>parent.loadHeadImg('"+list.get(0)+"');</script>";
	}

	/**
	 * 更新用户头像 user/id.png
	 * @author GaoYuan
	 * @datetime 2018/1/27 下午5:04
	 */
	@RequestMapping(value = "/uploadHeadImgSelf", method = RequestMethod.POST)
	public @ResponseBody String uploadHeadImgSelf(@RequestParam("file") MultipartFile[] files,
											HttpServletRequest request) {
		List<String> list = Lists.newArrayList();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				MultipartFile file = files[i];
//				list = saveFile(request, file, list);
				// 判断文件是否为空
				if (!file.isEmpty()) {
					try {
						// 保存的文件路径(如果用的是Tomcat服务器，文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
						// )
						String savePathPre = SysConfigUtil.getConfigValueByKey("UPLOAD_SAVE_PATH_IMG","");
						String readPath = "/user/"+UserUtils.getUserId()+".png";
						String filePath = savePathPre + readPath;

						File saveDir = new File(filePath);
						File oldFile = new File(filePath);
						if (!saveDir.getParentFile().exists()){
							saveDir.getParentFile().mkdirs();
						}
						if(oldFile.exists()){
							oldFile.delete();
						}
						// 转存文件
						file.transferTo(saveDir);
						list.add(readPath);

					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			if(list.size()>0){
				User user = new User();
				user.setId(UserUtils.getUserId());
				user.setPhoto(list.get(0));
				userService.updateHeadImg(user);
				olog("更新个人头像");
			}
		}
		//跳转的页面
		return "<script>parent.loadHeadImg('"+list.get(0)+"');</script>";
	}





}
